import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Image,
    Dimensions,
    ListView,
    TouchableOpacity,
    Platform,
    FlatList,
    TextInput,
    DeviceEventEmitter,
    KeyboardAvoidingView,
    ScrollView,
    UIManager
} from 'react-native';
import uuid from 'uuid';
import RNFetchBlob from 'react-native-fetch-blob'
import Request from '../common/Request'
import SYImagePicker from 'react-native-syan-image-picker'
import {Toast,ModalIndicator,Overlay} from 'teaset';
import Utils from '../common/Utils'
const {height, width} = Dimensions.get('window');
const STORAGE_KEY_TOKEN = '@AsyncStorageDemo:key_token';
const avatarSource=[];
import mqtt from '../common/mqtt'
import ChatItem from "./ChatItem";
import OverLayTakingPictures from "../compoment/OverLayTakingPictures";
import dismissKeyboard from 'react-native/Libraries/Utilities/dismissKeyboard'
export default class ChatInterfacePage extends Component {
    componentDidMount() {
        this._loadInitialState().done();
        this.msgListener = DeviceEventEmitter.addListener('IM',(listenerMsg) => {
            this.addChatData(listenerMsg);
        });
        dismissKeyboard();
        this._connect();
    }
    componentWillUnmount() {
        this.msgListener&&this.msgListener.remove();
    }
    async _loadInitialState(){
        try{
            let value=await AsyncStorage.getItem(STORAGE_KEY_TOKEN);
            if(value!==null){
                this._appendMessage(value);
            }else{
                this._appendMessage('');
            }
        }catch(error){
            this._appendMessage('AsyncStorage错误'+error.message);
        }
    }
    _appendMessage=(message)=>{
        this.setState({
            token:this.state.token.concat(message)
        },()=>{this.getInfo()});
    };
    getInfo=()=>{
        let params={
            "token":this.state.token,
            "userId":this.props.toID,
            "pageNum":this.state.page,
            "time":this.state.time
        };
        fetch(Config.baseApi+'/IM/selectCustomerByTopic',{
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: Utils.getParamsString(params)
        })
            .then((response) => response.json())
            .then((responseJson) => {
                if(responseJson.status===0){
                    if(responseJson.data.length===0){
                        if(this.state.page !=1){
                            Toast.message('没有更多的历史记录了');
                            this.setState({
                                data:responseJson.data.list.concat(this.state.data),
                                refreshing: false,
                                time:responseJson.data.time
                            })
                        }else {
                            this.setState({
                                data:responseJson.data.list.concat(this.state.data),
                                refreshing: false,
                                time:responseJson.data.time
                            })
                        }
                    }else {
                        this.setState({
                            data:responseJson.data.list.concat(this.state.data),
                            refreshing: false,
                            time:responseJson.data.time
                        })
                    }
                }else{
                    this.setState({
                        refreshing: false,
                    });
                    Toast.message(responseJson.msg);
                }
            })
            .catch((error) => {
                this.setState({
                    refreshing: false,
                });
                Toast.message(error);
            });
    };
    chatContactId=this.props.id;
    chatToClientId=this.props.toID;
    constructor(props) {
        super(props);
        this.state = {
            token:'',
            data:[],
            message:'',
            page:1,
            images:'',
            refreshing:false,
            isFistShow:false,
            head:'',
            time:''
        }
    };
    //提交聊天记录，因为可能会收到两条相同的消息，所以需要判断
    addChatData=(listenerMsg)=>{
        if(listenerMsg.userId==this.props.toID){
            const { data } = this.state;
            let a=0;
            if(data.length>1){
                for(let i=data.length-1;i<data.length;i++){
                    if(data[i].id==listenerMsg.id){
                        a+=1
                    }
                }
                if(a==0){
                    data.push(listenerMsg);
                    this.setState({ data });
                    this.FlatList.scrollToEnd()
                }
            }else {
                data.push(listenerMsg);
                this.setState({ data });
                this.FlatList.scrollToEnd()
            }
        }
    };
    _connect() {
        // TODO: 后期需要写到其他地方
        const toClientId = this.chatToClientId;
        const clientId = this.chatContactId;
        const params = {
            clientId,
            clean: true,
            username: 'wuxing',
            password: 'a1234567',
            reconnectPeriod: 3000, // 重连
        };
        this.client = mqtt.connect(Config.mqttUri, params);
        this.client.on('connect', (res) => {
            const topic = {};
            //topic[this.props.topic] = 1;
            topic[`layout/${toClientId}/customer${clientId}`] = 1;
            this.client.subscribe(topic);
        });
        this.client.on('reconnect', (res) => {
            const topic = {};
            topic[`layout/${toClientId}/customer${clientId}`] = 1;
            //topic[this.props.topic] = 1;
            this.client.subscribe(topic);
        });
        // 连接失败
        this.client.on('error', (error) => {
            Toast.message(JSON.stringify(error))
        });
    }
    //list中间
    middleView=()=>{
        return (
            <View style={{height:15,width:width}}/>
        )
    };
    //发送消息
    sendMessage=()=>{
        const {data}=this.state;
        if(this.state.message!==''){
            let params={
                "token":this.state.token,
                "object":{
                    "clientId":this.props.id,
                    "toClientId":this.props.toID,
                    "message":this.state.message,
                    "isCustomer":false
                }
            };
            ModalIndicator.show("正在请求数据......");
            fetch(Config.baseApi+'/IM/publish',{
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(params)
            })
                .then((response) => response.json())
                .then((responseJson) => {
                    ModalIndicator.hide();
                    if(responseJson.status===0){
                        const toClientId = this.chatToClientId;
                        const clientId=this.chatContactId;
                        const json = {
                            messageId: uuid(this.chatContactId), // 后端去实现唯一的 id
                            userId:clientId,
                            head:responseJson.data.head,
                            isMsg: false,
                            id:responseJson.data.id,
                            message: this.state.message,
                            votime:responseJson.data.time
                        };
                        this.client.publish(`layout/customer${clientId}/${toClientId}`, JSON.stringify(json), {
                            qos: 1,
                            retain: false
                        });
                        // this.client.publish(`layout/${toClientId}/customer${clientId}`, JSON.stringify(json), {
                        //     qos: 1,
                        //     retain: false
                        // });
                        const msg={userId:clientId,
                            head:responseJson.data.head,
                            isMsg: 0,
                            id:responseJson.data.id,
                            message: this.state.message,
                            votime:responseJson.data.time};
                        data.push(msg);
                        this.FlatList.scrollToEnd();
                        this.setState({
                            message:'',
                            data
                        })
                    }else{
                        Toast.message(responseJson.msg);
                    }
                })
                .catch((error) => {
                    ModalIndicator.hide();
                    Toast.message(error);
                });
        }else {
            Toast.message('请输入消息内容')
        }
    };
    //浮框
    showPop=(type, modal, text)=>{
        let overlayView = (
            <Overlay.PopView
                style={{flex:1,justifyContent:'flex-end'}}
                type={type}
                modal={modal}
                ref={v => this.overlayPopView = v}
            >
                <OverLayTakingPictures
                    pickSingleWithCamera={()=>{this.pickSingleWithCamera()}}
                    openPicLib={()=>this.openPicLib()}
                    ID={this.props.ID}
                    deleteOverlay={()=>this.overlayPopView && this.overlayPopView.close()}
                />
            </Overlay.PopView>
        );
        Overlay.show(overlayView);
    };
    //拍照
    pickSingleWithCamera=()=>{
        this.overlayPopView && this.overlayPopView.close();
        const options = {
            imageCount: 9,             // 最大选择图片数目，默认6
            isCamera: true,            // 是否允许用户在内部拍照，默认true
            isCrop: false,             // 是否允许裁剪，默认false
            showCropCircle: false,     // 是否显示圆形裁剪区域，默认false
        };
        SYImagePicker.openCamera(options, (err, selectedPhotos) => {
            if(err){
                return;
            }
            avatarSource.splice(0,avatarSource.length);
            for ( let i=0;i<selectedPhotos.length;i++) {
                avatarSource.push({
                    uri: selectedPhotos[i].uri,
                    width: selectedPhotos[i].width,
                    height: selectedPhotos[i].height,
                    mime: selectedPhotos[i].mime,
                });
            }
            let Num=avatarSource.length;
            if(Num>9){
                avatarSource.splice(9,Num-9)
            }
            this.setState({
                images: avatarSource
            },()=>{this.publishFile()});
        })
    };
    //从相册中选择
    openPicLib=()=>{
        this.overlayPopView && this.overlayPopView.close();
        const options = {
            imageCount: 9,             // 最大选择图片数目，默认6
            isCamera: false,            // 是否允许用户在内部拍照，默认true
            isCrop: false,             // 是否允许裁剪，默认false
            showCropCircle: false,     // 是否显示圆形裁剪区域，默认false
        };
        SYImagePicker.asyncShowImagePicker(options)
            .then(photos => {
                for ( let i=0;i<photos.length;i++) {
                    avatarSource.push({
                        uri: photos[i].uri,
                        width: photos[i].width,
                        height: photos[i].height,
                        mime: photos[i].mime,
                    });
                }
                let Num=avatarSource.length;
                if(Num>9){
                    avatarSource.splice(9,Num-9)
                }
                this.setState({
                    images: avatarSource
                },()=>{this.publishFile()});
            })
            .catch(err => {
                Toast.message(JSON.stringify(err))
            });
    };
    //转译图片
    publishFile=()=>{
        for(let i=0;i<this.state.images.length;i++){
            let body=[];
            body.push(
                {data:RNFetchBlob.wrap(this.state.images[i].uri),filename:'file',name:'file'}
            );
            Request.upload(Config.baseApi+'/file/upload',body,(progress)=>{

            },(data)=>{
                this.publishPhoto(data.data.targetName);
            },(error)=>{
                Toast.message(JSON.stringify(error));
            });
        }
    };
    //发送图片
    publishPhoto=(image)=>{
        const {data}=this.state;
        let params={
            "token":this.state.token,
            "object":{
                "clientId":this.props.id,
                "toClientId":this.props.toID,
                "photo":image,
                "isCustomer":false
            }
        };
        ModalIndicator.show("正在请求数据......");
        fetch(Config.baseApi+'/IM/publishFile',{
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(params)
        })
            .then((response) => response.json())
            .then((responseJson) => {
                ModalIndicator.hide();
                if(responseJson.status===0){
                    const toClientId = this.chatToClientId;
                    const clientId=this.chatContactId;
                    const json = {
                        messageId: uuid(this.chatContactId), // 后端去实现唯一的 id
                        userId:clientId,
                        head:responseJson.data.head,
                        isMsg: 1,
                        id:responseJson.data.id,
                        message:'',
                        photo:image,
                        votime:responseJson.data.time
                    };
                    this.client.publish(`layout/customer${clientId}/${toClientId}`, JSON.stringify(json), {
                        qos: 1,
                        retain: false
                    });
                    // this.client.publish(`layout/${toClientId}/customer${clientId}`, JSON.stringify(json), {
                    //     qos: 1,
                    //     retain: false
                    // });
                    const msg={userId:clientId,
                        head:responseJson.data.head,
                        isMsg: 1,
                        message:'',
                        id:responseJson.data.id,
                        photo:image,
                        votime:responseJson.data.time};
                    data.push(msg);
                    this.setState({
                        data
                    });
                    this.setState({
                        message:''
                    });
                    avatarSource.splice(0,avatarSource.length);
                    this.FlatList.scrollToEnd();
                    this.setState({
                        images:''
                    })
                }else{
                    Toast.message(responseJson.msg);
                }
            })
            .catch((error) => {
                ModalIndicator.hide();
                Toast.message(error);
            });
    };
    //下拉刷新
    onRefresh=()=>{
        this.setState({
            refreshing: true,
            page:this.state.page+1
        },()=>{
            this.getInfo();
        })
    };
    //返回
    goBack=()=>{
        let params={
            "token":this.state.token,
            "toClientId":this.props.toID,
        };
        ModalIndicator.show("正在请求数据......");
        fetch(Config.baseApi+'/IM/readMessage',{
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: Utils.getParamsString(params)
        })
            .then((response) => response.json())
            .then((responseJson) => {
                ModalIndicator.hide();
                if(responseJson.status===0){
                    if(this.props.callback){
                        this.props.callback('refresh');
                    }
                    this.client.end();
                    avatarSource.splice(0,avatarSource.length);
                    this.setState({
                        images:'',
                        message:''
                    });
                    Actions.pop();
                }else{
                    Toast.message(responseJson.msg);
                }
            })
            .catch((error) => {
                ModalIndicator.hide();
                Toast.message(error);
            });
    };

    header=()=>{
        return(
            <View style={{height:8,width:width}}/>
        )
    };

    render() {
        return (
            <View style={styles.container}>
                <View style={styles.titleView}>
                    <TouchableOpacity
                        onPress={()=>this.goBack()}
                        style={styles.goBackView}>
                        <Image
                            source={ImageUtil.return}
                            style={styles.titleLeftImg}/>
                    </TouchableOpacity>
                    <Text style={styles.titleMsg}>{this.props.nickname}</Text>
                </View>
                <KeyboardAvoidingView
                    behavior={'position'}
                    keyboardVerticalOffset={20}
                    style={styles.bottomView}>
                    <FlatList
                        ref={ (ref)=>this.FlatList = ref }
                        style={{height:height-119,width:width}}
                        data={this.state.data}
                        ListHeaderComponent={this.header}
                        ListFooterComponent={()=><View style={{height:10,width:width}}/>}
                        onRefresh={this.onRefresh}
                        refreshing={this.state.refreshing}
                        onContentSizeChange={this.state.page==1?()=>this.FlatList.scrollToEnd():null}
                        ItemSeparatorComponent={this.middleView}
                        renderItem={(item)=><ChatItem
                            item={item}
                            ID={this.props.ID}
                            refresh={()=>{
                                this.setState({
                                    page:1,
                                    time:'',
                                    data:[]
                                },()=>this.getInfo());
                            }}
                            toID={this.props.toID}
                            id={this.props.id}/>}
                        keyExtractor={(item, index) => index}
                    />
                    <View style={{height:0.5,width:width,backgroundColor:'#e2e2e3'}}/>
                    <View style={{flexDirection:'row',alignItems:'center',height:55,width:width,backgroundColor:'#f8f8f8'}}>
                        <TouchableOpacity onPress={()=>this.showPop('zoomOut', true, 'Pop modal')}>
                            <Image
                                source={ImageUtil.addShopping}
                                style={{height:23,width:23,borderRadius:23/2,marginLeft:15}}/>
                        </TouchableOpacity>
                        <TextInput
                            ref={ (ref)=>this.TextInput = ref }
                            autoCapitalize={"none"}
                            underlineColorAndroid={'transparent'}
                            autoCorrect={false}
                            enablesReturnKeyAutomatically
                            multiline
                            numberOfLines={4}
                            maxLength={800}
                            spellCheck={false}
                            value={this.state.message}
                            returnKeyLabel="换行"
                            style={styles.textInputView}
                            onChangeText={(text)=>{
                                this.setState({
                                    message:text,
                                })
                            }}/>
                        <TouchableOpacity
                            onPress={()=>this.sendMessage()}
                            style={styles.ButView}>
                            <Text style={{fontSize:16,color:this.props.ID=='suppliers'? suppliersThemeColor : PurchaserThemeColor,textAlign:'center'}}>发送</Text>
                        </TouchableOpacity>
                    </View>
                </KeyboardAvoidingView>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        height:Platform.OS==='ios'? height : height-20,
        width:width,
        backgroundColor: '#f0f0f0'
    },
    titleView:{
        height:iOS?64:44,
        paddingTop:iOS?20:0,
        alignItems:'center',
        justifyContent:'center',
        borderBottomWidth:0.5,
        borderColor:'#dbdbdb',
        backgroundColor:'#ffffff'
    },
    goBackView:{
        position: 'absolute',
        left:15,
        height:iOS?64:44,
        paddingTop:iOS?20:0,
        justifyContent:'center',
        backgroundColor:'rgba(0,0,0,0)'
    },
    titleLeftImg:{
        height:20,
        width:20
    },
    titleMsg:{
        color:'#000',
        fontSize:17
    },
    titleRightView:{
        position: 'absolute',
        right:15,
        height:iOS?64:44,
        paddingTop:iOS?20:0,
        justifyContent:'center',
        backgroundColor:'rgba(0,0,0,0)'
    },
    titleRightMsg:{

    },
    labelView:{
        flexDirection:'row',
        width:width-123,
    },
    headImg: {
        marginLeft:15,
        height:44,
        width:44,
        borderRadius:22,
    },
    labelMsgView:{
        borderBottomRightRadius:15,
        borderTopRightRadius:15,
        borderBottomLeftRadius:15,
        marginLeft:10,
        shadowOffset: {width: 0, height: 5},
        shadowOpacity: 0.2,
        shadowRadius: 5,
        shadowColor: '#000000',
        elevation:5
    },
    labelMsg:{
        fontSize:14,
        marginTop:15,
        marginBottom:15,
        marginLeft:16,
        marginRight:16,
        color:'#000000',
        backgroundColor:'rgba(0,0,0,0)'
    },
    labelViewChange:{
        flexDirection:'row',
        justifyContent:'flex-end',
        width:width-123,
        marginLeft:123,
    },
    headImgChange:{
        marginRight:15,
        width:44,
        height:44,
        borderRadius:22
    },
    labelMsgViewChange:{
        marginRight:10,
        borderBottomRightRadius:15,
        borderBottomLeftRadius:15,
        borderTopLeftRadius:15,
        backgroundColor:'#ffffff',
        shadowOffset: {width: 0, height: 5},
        shadowOpacity: 0.2,
        shadowRadius: 5,
        shadowColor: '#000000',
        elevation:5
    },
    textInputView:{
        height:39,
        backgroundColor:'#ffffff',
        color:'#000000',
        fontSize:20,
        borderRadius:5,
        width:width-120,
        marginLeft:15,
        padding:0,
        paddingLeft:5
    },
    ButView:{
        marginLeft:5,
        height:44,
        width:60,
        alignItems:'center',
        justifyContent:'center',
    },
    PopMsg:{
        textAlign:'center',
        fontSize:15,
        color:PurchaserThemeColor,
    },
    overlay1:{
        height:44,
        width:width-10,
        borderRadius:10,
        alignItems:'center',
        justifyContent:'center',
        backgroundColor:'#ffffff',
        marginTop:5,
        marginBottom:10
    },
    overlay:{
        height:44,
        width:width-10,
        alignItems:'center',
        justifyContent:'center',
        backgroundColor:'#ffffff'
    },
    bottomView:{
        justifyContent:'flex-end',
        position:'absolute',
        zIndex:-1,
        top:44,
        right:0,
        bottom:0,
        left:0,
    }
});
